package factory;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.JTextComponent;
import javax.swing.undo.UndoManager;

public class UndoManagerFactory {
    public static UndoManager appendUndoManagerToTextComponent(JTextComponent component) {
        UndoManager undoManager = new UndoManager();
        component.getDocument().addUndoableEditListener(new LibraryUndoableEditListener(undoManager));
        appendKeyListener(component, undoManager);
        return undoManager;
    }

    private static void appendKeyListener(JTextComponent component, final UndoManager undoManager) {
        component.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent arg0) {}

            @Override
            public void keyReleased(KeyEvent arg0) {}

            @Override
            public void keyPressed(KeyEvent arg0) {
                if ((arg0.getModifiers() & KeyEvent.CTRL_MASK) != 0) {
                    if (arg0.getKeyCode() == KeyEvent.VK_Z)
                        if (undoManager.canUndo())
                            undoManager.undo();
                    if (arg0.getKeyCode() == KeyEvent.VK_Y)
                        if (undoManager.canRedo())
                            undoManager.redo();
                }
            }
        });
    }

    private static class LibraryUndoableEditListener implements UndoableEditListener {
        UndoManager manager;

        public LibraryUndoableEditListener(UndoManager undoManager) {
            manager = undoManager;
        }

        @Override
        public void undoableEditHappened(UndoableEditEvent e) {
            manager.addEdit(e.getEdit());
        }
    }

}
